<?php
namespace app\task\controller;

use hema\wechat\Driver;
use app\task\model\Applet as AppletModel;
use app\task\model\Wechat as WechatModel;
use app\task\model\User as UserModel;
use think\facade\Session;

/**
 * 授权回调接口
 */

class Auth extends \app\BaseController
{
	/**
     * 微信扫码登录
     */
    public function login(string $code = '',$state = 0)
    {
    	$wx = new Driver;
    	//通过code获取access_token
        $result = $wx->getWebToken($code);
        //如果获取access_token失败
	    if(!isset($result['access_token'])){
	    	die(json_encode(['code' => 0, 'msg' => '获取access_token失败']));
	    }
	    //获取用户信息
	    $url = 'https://api.weixin.qq.com/sns/userinfo';
        $result = $wx->getUserinfo($result['openid'],$result['access_token']);
        //如果获取成功
        if(isset($result['unionid'])){
        	$data = [
        		'union_id' => $result['unionid'],
				//'open_id' => $result['openid'],
				'nickname' => preg_replace('/[\xf0-\xf7].{3}/', '', $result['nickname']),
				'avatar' => $result['headimgurl'],
				'gender' => $result['sex'],
				'country' => $result['country'],
				'province' => $result['province'],
				'city' => $result['city'],
				'status' => 20, //商户管理
			];
        	if(!$user = UserModel::where('union_id',$data['union_id'])->where('status','>',10)->find()){
				$user = new UserModel;
				$user->save($data);
				$user = UserModel::where('union_id',$data['union_id'])->where('status','>',10)->find();
			}
			// 保存登录状态
			Session::set('hema_store', [
				'user' => $user,
				'is_login' => true,
				'is_admin' => true,
			]);
		}else{
			die(json_encode(['code' => 0, 'msg' => '获取用户信息失败']));
		}
		return redirect('/user');
	}
	/**
     * 公众号授权
     */
    public function wechat($applet_id = 0, string $app_type = '')
    {
		$auth_code = empty ( $_GET ['auth_code'] ) ?"" : trim ( $_GET ['auth_code'] );	//获取授权码
		if(!empty($auth_code)){
			$wx = new Driver;
			//获取授权信息
			$result = $wx->getAuth($auth_code);
			$auth = $result['authorization_info'];//得到授权信息
			//获取授权应用的帐号基本信息
			$result = $wx->getAppInfo($auth['authorizer_appid']);
			$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
			if($wechat = WechatModel::getWechat(['applet_id' => $applet_id])){
				if($wechat['app_id'] != $auth['authorizer_appid']){
					//切换授权 - 清除历史数据
					$wechat->clear($applet_id);
				}
			}else{
				$wechat = new WechatModel;
			}
			$wechat->save([
				'app_id' => $auth['authorizer_appid'],//授权方APPid
				'user_name' => $app['user_name'],//原始ID
				'app_name' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
				'head_img' => isset($app['head_img'])?$app['head_img']:'',//头像
				'qrcode_url' =>$app['qrcode_url'],	//二维码地址
				'principal_name' => $app['principal_name'],	//主体名称
				'access_token' => $auth['authorizer_access_token'],	//令牌
				'expires_in' => time()+7000,//令牌过期时间
				'authorizer_refresh_token' => $auth['authorizer_refresh_token'],//刷新令牌	
				'applet_id' => $applet_id,	
				'status' => 1	//是否授权		
			]);
			if($applet_id > 0){
				return redirect('/store/' . $app_type . '.wechat/index');
			}
			return redirect('/admin/wechat/index');
		}
		echo "error";
	}

	/**
     * 小程序授权
     */
    public function applet($applet_id = 0, string $app_type = '')
    {
		$auth_code = empty ( $_GET ['auth_code'] ) ?"" : trim ( $_GET ['auth_code'] );	//获取授权码
		if(!empty($auth_code)){
			$wx = new Driver;
			//获取授权信息
			$result = $wx->getAuth($auth_code);
			$auth = $result['authorization_info'];//得到授权信息
			$applet = AppletModel::get($applet_id);
			//获取授权应用的帐号基本信息
			$result = $wx->getAppInfo($auth['authorizer_appid']);
			$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
			if($applet['app_id'] != $auth['authorizer_appid']){
				//切换授权 - 清除历史数据
				//$model = new AppletModel;
				$applet->clear($applet_id);
			}
			$api_domain = '';
            $signature = '';
            //添加服务器域名
            $serveDomain = $wx->setServeDomain(0,'',$auth['authorizer_access_token']);
            if($serveDomain['errcode'] == 0){
                $api_domain = $serveDomain['apiurl'];
            }
            //设置小程序简介
            $setSignature = $wx->setSignature(0,'',$auth['authorizer_access_token']);
            if($setSignature['errcode'] == 0){
                $signature = $setSignature['signature'];
            }
			$applet->save([
				'app_name' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
				'head_img' => isset($app['head_img'])?$app['head_img']:'',		//头像
				'qrcode_url' => isset($app['qrcode_url'])?$app['qrcode_url']:'',	//二维码
				'user_name' => $app['user_name'],					//原始ID
				'principal_name' => $app['principal_name'],			//主体名称
				'signature' => $signature,	//账号介绍
				'api_domain' => $api_domain,//服务器域名
				'app_id' => $auth['authorizer_appid'],				//授权方APPid
				'access_token' => $auth['authorizer_access_token'],	//令牌
				'expires_in' => time()+7000,						//令牌过期时间
				'authorizer_refresh_token' => $auth['authorizer_refresh_token'],	//刷新令牌
				'status' => 1	//是否授权				
			]);
			// 保存授权状态
			$applet = AppletModel::get($applet_id);
			Session::set('hema_store.applet',$applet);
			return redirect('/store/' . $app_type . '.applet/index');
		}
		echo "error";
	}
}
